<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  news
 */

class m_news_actions_block_front_NewsHighlightsAction extends f_core_Action
{
	public function execute()
	{
        $blockParams = $this->getBlockContext()->getParameters();
        $provider = $this->getDocumentProvider();

        $folderNewsId = null;
        $page = null;
  
        if(isset($blockParams['pageNewsId']) && !empty($blockParams['pageNewsId']))
        {
            $page = $provider->getByModelAndUniqueId("modules_website/page", $blockParams["pageNewsId"], $blockParams['blockLang']);
            $blocks = $page->getAllBlocks();

            if(!empty($blocks))
            {
                foreach($blocks as $block)
                {
                    if(array_key_exists("folderNewsId", $block))
                    {
                        $folderNewsId = $block["folderNewsId"];
                    }
                }
            }
        }

        if(empty($folderNewsId) && isset($blockParams['folderId']) && !empty($blockParams['folderId']))
        {
            $folderNewsId = $blockParams['folderId'];
        }

        $news = $this->getNews($blockParams, $folderNewsId);
        $news = m_news_services_ItemService::getInstance()->getNewsArray($news, $page);

        $urlPage = !is_null($page) ? $page->getCompleteUrl() : "#";

        $this->addToModel("urlPage", $urlPage);
        $this->addToModel("blockParams", $blockParams);
        $this->addToModel("news", $news);
        $this->setView('success');

	}	
	
	public function validate()
	{
		return true;
	}
	
	public function errorHandler()
	{
		$this->setView('error');
	}

    private function getNews($blockParams, $folderNewsId)
    {
        $news = $this->getDocumentProvider()
                                    ->loadDocuments("modules_news/item")
                                    ->byPublicationStatus("PUBLISHED")
                                    ->whereIsPublicationDatesValid();

        if(!empty($folderNewsId))
        {
            $news->isChildOf($folderNewsId, "item", true);
            $news->addAscOrder("relation_order");
        }

        if(isset($blockParams['limit']) && $blockParams['limit'] != 0)
        {
            $news->limit($blockParams["limit"]);
        }

        return $news->addDescOrder("document_startpublicationdate")
                     ->retrieveDocuments($blockParams["blockLang"]);
        
    }
}